#!/usr/bin/env python
"""
登录功能诊断脚本
用于检查后端登录接口的配置是否正确
"""
import os
import sys
from pathlib import Path

# 添加项目路径
BASE_DIR = Path(__file__).resolve().parent
sys.path.append(str(BASE_DIR))

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'massage_app.settings')

try:
    import django
    django.setup()
except Exception as e:
    print(f"❌ Django初始化失败: {e}")
    sys.exit(1)

def check_env_variables():
    """检查环境变量"""
    print("\n" + "="*60)
    print("1️⃣  检查环境变量配置")
    print("="*60)
    
    from django.conf import settings
    
    checks = {
        'SECRET_KEY': settings.SECRET_KEY,
        'DEBUG': settings.DEBUG,
        'WECHAT_APP_ID': settings.WECHAT_APP_ID,
        'WECHAT_APP_SECRET': settings.WECHAT_APP_SECRET,
    }
    
    for key, value in checks.items():
        if value:
            if key in ['SECRET_KEY', 'WECHAT_APP_SECRET']:
                display_value = value[:10] + '...' if len(value) > 10 else value
            else:
                display_value = value
            print(f"   ✅ {key}: {display_value}")
        else:
            print(f"   ❌ {key}: 未配置")
            if key in ['WECHAT_APP_ID', 'WECHAT_APP_SECRET']:
                print(f"      → 请在 .env 文件中配置")

def check_database():
    """检查数据库"""
    print("\n" + "="*60)
    print("2️⃣  检查数据库连接")
    print("="*60)
    
    try:
        from django.db import connection
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
        print("   ✅ 数据库连接正常")
        
        # 检查表是否存在
        from django.db import connection
        tables = connection.introspection.table_names()
        
        required_tables = ['user_info', 'technician_info', 'order_info', 'service_item']
        for table in required_tables:
            if table in tables:
                print(f"   ✅ 表 {table} 存在")
            else:
                print(f"   ❌ 表 {table} 不存在")
                print(f"      → 请运行: python manage.py migrate")
                
    except Exception as e:
        print(f"   ❌ 数据库连接失败: {e}")

def check_user_model():
    """检查用户模型"""
    print("\n" + "="*60)
    print("3️⃣  检查用户模型")
    print("="*60)
    
    try:
        from accounts.models import User
        user_count = User.objects.count()
        print(f"   ✅ User模型正常，当前用户数: {user_count}")
    except Exception as e:
        print(f"   ❌ User模型异常: {e}")

def check_urls():
    """检查URL配置"""
    print("\n" + "="*60)
    print("4️⃣  检查URL路由配置")
    print("="*60)
    
    try:
        from django.urls import resolve
        
        # 检查登录接口路由
        try:
            resolve('/api/auth/wx_login/')
            print("   ✅ 登录接口路由 /api/auth/wx_login/ 已配置")
        except Exception:
            print("   ❌ 登录接口路由未找到")
            
    except Exception as e:
        print(f"   ❌ URL检查失败: {e}")

def check_cors():
    """检查CORS配置"""
    print("\n" + "="*60)
    print("5️⃣  检查CORS跨域配置")
    print("="*60)
    
    try:
        from django.conf import settings
        
        if 'corsheaders' in settings.INSTALLED_APPS:
            print("   ✅ corsheaders 已安装")
        else:
            print("   ❌ corsheaders 未安装")
            
        if hasattr(settings, 'CORS_ALLOW_ALL_ORIGINS'):
            print(f"   ✅ CORS_ALLOW_ALL_ORIGINS: {settings.CORS_ALLOW_ALL_ORIGINS}")
        else:
            print("   ⚠️  未配置 CORS_ALLOW_ALL_ORIGINS")
            
    except Exception as e:
        print(f"   ❌ CORS检查失败: {e}")

def test_wechat_api():
    """测试微信API"""
    print("\n" + "="*60)
    print("6️⃣  测试微信登录功能")
    print("="*60)
    
    try:
        from accounts.services import UserService
        from django.conf import settings
        
        # 使用测试code
        result = UserService.wechat_login('test_code', 'TestUser', 'http://test.com/avatar.jpg')
        
        print("   ✅ 微信登录接口调用成功")
        print(f"   - 用户ID: {result['user']['id']}")
        print(f"   - 用户名: {result['user']['username']}")
        print(f"   - 角色: {result['user']['role']}")
        print(f"   - Token长度: {len(result['access'])} 字符")
        
    except Exception as e:
        print(f"   ❌ 微信登录测试失败: {e}")
        import traceback
        print(traceback.format_exc())

def check_dependencies():
    """检查依赖包"""
    print("\n" + "="*60)
    print("7️⃣  检查Python依赖包")
    print("="*60)
    
    required_packages = [
        'django',
        'djangorestframework',
        'djangorestframework_simplejwt',
        'corsheaders',
        'wechatpy',
        'requests',
    ]
    
    for package in required_packages:
        try:
            __import__(package)
            print(f"   ✅ {package} 已安装")
        except ImportError:
            print(f"   ❌ {package} 未安装")
            print(f"      → 请运行: pip install {package}")

def main():
    """主函数"""
    print("\n" + "🔍 开始诊断登录功能配置".center(60, "="))
    
    check_env_variables()
    check_dependencies()
    check_database()
    check_user_model()
    check_urls()
    check_cors()
    test_wechat_api()
    
    print("\n" + "="*60)
    print("✅ 诊断完成！")
    print("="*60)
    print("\n如果所有检查都通过，登录功能应该可以正常使用。")
    print("如果仍有问题，请检查：")
    print("  1. 后端服务是否在 http://localhost:8000 运行")
    print("  2. 小程序是否开启了'不校验合法域名'选项")
    print("  3. 查看小程序控制台和后端日志的详细错误信息\n")

if __name__ == '__main__':
    main()

